using System;
using System.Collections.Generic;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.Core.Interceptor;
using Castle.MicroKernel.Facilities;

namespace Castle.Facilities.PolicyInjection
{
    public class ComponentPolicy
    {
        private IList<Rule> _ruleCollection;

        public IList<Rule> RuleCollection
        {
            get
            {
                return _ruleCollection;
            }
        }               

        private string _componentId;

        public string ComponentId
        {
            get
            {
                return _componentId;
            }
        }

        public ComponentPolicy(IConfiguration configuration, PolicyFacility facility, string componentId, ComponentModel componentModel)
        {
            InspectTagElement(configuration);
            CreateRuleCollection(configuration, facility, componentId, componentModel);
            _componentId = componentId;            
        }        

        private void InspectTagElement(IConfiguration configuration)
        {
            if (configuration.Name != Literals.policy)
            {
                throw new InvalidOperationException("Policy element must be <policy>");
            }
            if (configuration.Children.Count == 0)
            {
                throw new InvalidOperationException("Policy element must have at least one child element <rule>");
            }
        }

        private void CreateRuleCollection(IConfiguration configuration, PolicyFacility facility, string componentId, 
            ComponentModel componentModel)
        {
            _ruleCollection = new List<Rule>();
            foreach (IConfiguration ruleConfiguration in configuration.Children)
            {
                Rule rule = new Rule(ruleConfiguration, facility, componentId, componentModel);
                _ruleCollection.Add(rule);
            }
        }      
    }
}
